<?php
/* ******************************
	Incoming Tasks aJax actions
   ******************************
*/
	include('../../includes/classes/core.php');
	$action = $_REQUEST['act'];
	$start	= $_REQUEST['start'];
	
	switch ($action) {
	    case 'get_list':
    	    $count = $_REQUEST['count'];
    	    
    	    $rResult = mysql_query("SELECT    		production.id AS `id`,
													production.`code` AS `code`,
													production.`name` AS `name`,
													production_unit.`name` AS `unit`,
													SUM(reserve.quantity) - SUM(IF(ISNULL(sale_transaction_detail.product_quantity), 0, sale_transaction_detail.product_quantity))  AS `quantity`,
													IF(ISNULL(sale_transaction_detail.self_cost) OR sale_transaction_detail.self_cost = 0, ROUND(reserve.price, 2), ROUND(sale_transaction_detail.self_cost,2)) AS `self_cost`,
													(SUM(reserve.quantity) - SUM(IF(ISNULL(sale_transaction_detail.product_quantity), 0, sale_transaction_detail.product_quantity))) * (IF(ISNULL(sale_transaction_detail.self_cost) OR sale_transaction_detail.self_cost = 0, ROUND(reserve.price, 2), sale_transaction_detail.self_cost)) AS total
									FROM     		`sale_transaction`
									LEFT JOIN 		sale_transaction_detail ON sale_transaction.id = sale_transaction_detail.transaction_id 
									RIGHT JOIN 		reserve ON reserve.production_id = sale_transaction_detail.production_id AND DATE(sale_transaction.end_date) <= '$start'
									LEFT JOIN 		production ON production.id = reserve.production_id
									LEFT JOIN 		production_unit ON production_unit.id = production.unit
									LEFT JOIN 		production_category ON production_category.id = production.category
									WHERE   		DATE(reserve.create_date) <= '$start'
									GROUP BY 		reserve.production_id
    	    						HAVING			SUM(reserve.quantity) - SUM(IF(ISNULL(sale_transaction_detail.product_quantity), 0, sale_transaction_detail.product_quantity)) != 0");
			
			$output = array(
				"aaData"	=> array()
			);
			
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];
				}
				$output['aaData'][] = $row;
			}
			
			echo json_encode( $output );

	        break;	    
	    default:
	       	echo "null";
	}
?>